package userserv

import (
	"codedef"
	"encoding/json"
	"log"
	"net/http"
	"rhelper"
)

func modifyDevNoteName(w http.ResponseWriter, r *http.Request) {
	var uniqueId string
	uniqueId = r.Header.Get("uniqueId")

	log.Printf("modifyDevNoteName, uniqueId:%s\n", uniqueId)

	if r.ContentLength < 1 {
		log.Println("modifyDevNoteName failed, content length is zero")
		replyError(w, codedef.ERR_REQUEST_INVALID_PARAM)
		return
	}

	message := make([]byte, r.ContentLength)
	n, _ := r.Body.Read(message)
	if n != int(r.ContentLength) {
		log.Println("modifyDevNoteName failed, can't read request body")
		replyError(w, codedef.ERR_REQUEST_INVALID_PARAM)
		return
	}

	//log.Println("createPlan, receve message: ", string(message))
	ci := ControllerInfo{}
	err := json.Unmarshal(message, &ci)
	if err != nil {
		log.Println("modifyDevNoteName failed, json decode failed:", err)
		replyError(w, codedef.ERR_DECODE)
		return
	}

	if !isUserDeviceExist(uniqueId, ci.Id) {
		log.Println("onLoadDevice failed, controller not exist ", ci.Id)
		replyError(w, codedef.ERR_CONTROLLER_NOT_EXIST)
		return
	}

	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	_, err = rconn.Do("HSET", rhelper.ControllerHash+ci.Id, "alias", ci.Alias)
	if err != nil {
		log.Println("Set alias failed,", err)
		replyError(w, codedef.ERR_DATABASE)
	}
	rb := map[string]string{
		"status": "200",
	}
	replyJSON(w, rb)
}
func init() {
	myMux.muxHandlers.HandleFunc("/modifyDevNoteName", modifyDevNoteName)
}
